package jmine.tec.database.query.condition;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import jmine.tec.database.query.Condition;

import org.apache.commons.lang.StringUtils;

/**
 * Condição de conjunção de várias condições
 * 
 * @author lundberg
 */
public class AndCondition implements Condition {

    private List<Condition> conditions = new ArrayList<Condition>();

    /**
     * Construtor
     * 
     * @param initialConditions initialConditions
     */
    public AndCondition(Condition... initialConditions) {
        this.conditions.addAll(Arrays.asList(initialConditions));
    }

    /**
     * {@inheritDoc}
     */
    public String createQueryCondition() {
        List<String> queryConditions = new ArrayList<String>();
        for (Condition condition : this.conditions) {
            queryConditions.add(condition.createQueryCondition());
        }
        return StringUtils.join(queryConditions, " AND ");
    }

    /**
     * {@inheritDoc}
     */
    public int setParameters(PreparedStatement st, int parameterIndex) throws SQLException {
        int currentIndex = parameterIndex;
        for (Condition condition : this.conditions) {
            currentIndex = condition.setParameters(st, currentIndex);
        }
        return currentIndex;
    }

    /**
     * Adiciona uma condição à conjunção.
     * 
     * @param condition condition
     * @return self
     */
    public AndCondition addCondition(Condition condition) {
        this.conditions.add(condition);
        return this;
    }
}
